package com.xjd.transport.work;

import com.xjd.transport.TransportStates;
import com.xjd.transport.impl.FutureImpl;

public abstract class Work extends Thread implements TransportStates {
	protected FutureImpl future;
	protected WorkExecutor executor;

	protected boolean cancelling = false;

	public Work(FutureImpl future) {
		this.future = future;
		this.future.setWork(this);
	}

	public void setExecutor(WorkExecutor executor) {
		this.executor = executor;
	}

	public boolean cancel() {
		synchronized (future.getStateLock()) {
			cancelling = true;
			synchronized (executor.workQueue) {
				if (executor.workQueue.contains(this)) { // 还没取出来，即还没执行
					executor.workQueue.remove(this); // 直接移除
					
					future.setState(STATE_STOPED);
					future.setFinishState(FINISH_STATE_CACELLED);
					future.getStateLock().notifyAll();
					future.fireFutureListener();
					return true;
				}
			}
			//已经取出来了，可能即将、正在、已经执行
			if (future.isDone()) { //完成
				if (future.isCancelled()) {
					return true;
				}
				return false;
			}
			future.awaitUninterruptibly(); //等待
			return future.isCancelled();
		}
	}

	public void run() {
		synchronized (future.getStateLock()) {
			future.setState(STATE_STARTED);
			future.getStateLock().notifyAll();
		}
		doWork();
		executor.executeNext();
	}

	public abstract void doWork();

}
